package algotithm.leetcode.listnode.test21;

import algotithm.leetcode.listnode.ListNode;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/17-9:59
 * @URL https://leetcode-cn.com/problems/merge-two-sorted-lists/
 * @Title 21. 合并两个有序链表
 */
public class Solution {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node11 = new ListNode(2);
        ListNode node111 = new ListNode(4);

        node1.next = node11;
        node11.next = node111;

        ListNode node2 = new ListNode(1);
        ListNode node22 = new ListNode(3);
        ListNode node222 = new ListNode(4);

        node2.next = node22;
        node22.next = node222;

        Solution solution = new Solution();
        ListNode listNode = solution.mergeTwoLists(node1, node2);
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }

        System.out.println();

//        ListNode listNode2 = solution.mergeTwoLists2(node1, node2);
//        while (listNode2 != null) {
//            System.out.print(listNode2.val + " ");
//            listNode2 = listNode2.next;
//        }
    }

    /**
     * 方法一 递归
     * @param l1 第一个链表头部
     * @param l2 第二个链表头部
     * @return listNode
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next,l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }
    }

    /**
     * 方法一 迭代
     * @param l1 第一个链表头部
     * @param l2 第二个链表头部
     * @return listNode
     */
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode preHead = new ListNode(-1);
        ListNode head = preHead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                head.next = l1;
                l1 = l1.next;
            } else {
                head.next = l2;
                l2 = l2.next;
            }
            head = head.next;
        }
        head.next = l1 != null ? l1 : l2;
        return preHead.next;
    }
}
